package Java.view.Common;

import Java.utils.CodeUtils;
import Java.utils.JDBC;
import domain.User;
import javafx.application.Application;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.*;
import javafx.stage.Stage;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Objects;

public class LoginFX extends Application {
    User user;
    private String codeText = "";
    private String usernameText = "";
    private String passwordText = "";
    private String rightcodeText = "";

    private TextField usernameField = new TextField();
    private PasswordField passwordField = new PasswordField();
    private TextField codeField = new TextField();
    private Label rightCodeLabel = new Label();
    private Label forgetPasswordLabel = new Label();
    private Button loginButton = new Button();
    private Button registerButton = new Button();

    public LoginFX(User user) {
        this.user=user;
    }

    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("斗地主登录");
        primaryStage.getIcons().add(new Image("file:src/image/dizhu.png"));

        StackPane root = new StackPane();
        root.setPadding(new Insets(98, 0, 0, 125));

        // 背景图片
        BackgroundImage myBI = new BackgroundImage(new Image("file:src/image/login/shouye1.png", 620, 405, false, true),
                BackgroundRepeat.NO_REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.DEFAULT,
                BackgroundSize.DEFAULT);
        root.setBackground(new Background(myBI));
        root.setBackground(new Background(myBI));

        // 创建 GridPane 布局
        GridPane grid = createForm();
        StackPane.setAlignment(grid, Pos.CENTER);

        // 创建按钮图像
        Image loginImage = new Image("file:src/image/login/登录按钮.png");
        Image registerImage = new Image("file:src/image/login/注册按钮.png");
        ImageView loginImageView = new ImageView(loginImage);
        ImageView registerImageView = new ImageView(registerImage);

        // 设置登录按钮的图像和样式
        loginButton.setGraphic(loginImageView);
        loginButton.setStyle("-fx-padding: 0; -fx-background-color: transparent; -fx-border-width: 0;");
        loginButton.setOnAction(e -> handleLogin());
        loginButton.setOnMousePressed(e -> loginButton.setGraphic(new ImageView(new Image("file:src/image/login/登录按下.png"))));
        loginButton.setOnMouseReleased(e -> loginButton.setGraphic(loginImageView));
        loginButton.setCursor(javafx.scene.Cursor.HAND); // 设置手形光标
        // 设置注册按钮的图像和样式
        registerButton.setGraphic(registerImageView);
        registerButton.setStyle("-fx-padding: 0; -fx-background-color: transparent; -fx-border-width: 0;");
        registerButton.setOnAction(e -> handleRegister());
        registerButton.setOnMousePressed(e -> registerButton.setGraphic(new ImageView(new Image("file:src/image/login/注册按下.png"))));
        registerButton.setOnMouseReleased(e -> registerButton.setGraphic(registerImageView));
        registerButton.setCursor(javafx.scene.Cursor.HAND); // 设置手形光标
        // 创建按钮容器 HBox
        HBox buttonBox = new HBox(35, loginButton, registerButton);
        buttonBox.setAlignment(Pos.CENTER);
        buttonBox.setPadding(new Insets(-10,40,0,-40)); // 设置适当的内边距
        // 创建按钮容器 VBox
        VBox vbox = new VBox(10, grid, buttonBox);
        vbox.setAlignment(Pos.CENTER);
        vbox.setPadding(new Insets(20)); // 增加外边距以避免组件重叠

        // 将背景图片、VBox 添加到根节点
        root.getChildren().add(vbox);

        Scene scene = new Scene(root, 600, 380);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    private GridPane createForm() {
        GridPane grid = new GridPane();
        grid.setVgap(22); // 行间距
        grid.setHgap(10); // 列间距
        grid.setPadding(new Insets(-10, 20, 30, 20)); // 内边距
        grid.setAlignment(Pos.CENTER); // 对齐方式

        // 设置列约束
        ColumnConstraints column1 = new ColumnConstraints();
        column1.setHalignment(HPos.RIGHT);
        ColumnConstraints column2 = new ColumnConstraints();
        ColumnConstraints column3 = new ColumnConstraints();
        column3.setHalignment(HPos.LEFT);
        grid.getColumnConstraints().addAll(column1, column2, column3);

        // 设置行约束
        RowConstraints row1 = new RowConstraints();
        RowConstraints row2 = new RowConstraints();
        RowConstraints row3 = new RowConstraints();
        RowConstraints row4 = new RowConstraints();
        grid.getRowConstraints().addAll(row1, row2, row3, row4);

        if(user!=null){
            usernameText=user.getUsername();
        }

        // 设置输入框宽度
        usernameField.setText(usernameText);
        usernameField.setPrefWidth(160);
        grid.add(usernameField, 1, 0);

        passwordField.setPrefWidth(160);
        grid.add(passwordField, 1, 1);

        codeField.setPrefWidth(160);
        grid.add(codeField, 1, 2);

        // 设置验证码图片
        rightcodeText = CodeUtils.getCode();
        rightCodeLabel.setText(rightcodeText);
        rightCodeLabel.setStyle("-fx-border-color: gray; -fx-background-color: white; -fx-padding: 5;");
        rightCodeLabel.setMinSize(55, 30);  // 设置最小大小
        rightCodeLabel.setAlignment(Pos.CENTER);  // 文字居中显示
        rightCodeLabel.setOnMouseClicked(e -> {
            rightcodeText = CodeUtils.getCode();
            rightCodeLabel.setText(rightcodeText);
        });
        rightCodeLabel.setCursor(javafx.scene.Cursor.HAND);
        grid.add(rightCodeLabel, 2, 2);

        // 忘记密码链接
        forgetPasswordLabel.setText("忘记密码？");
        forgetPasswordLabel.setStyle("-fx-text-fill: yellow;");
        forgetPasswordLabel.setOnMouseClicked(e -> handleForgetPassword());
        grid.add(forgetPasswordLabel, 2, 1);
        forgetPasswordLabel.setCursor(javafx.scene.Cursor.HAND); // 设置手形光标
        return grid;
    }

    private void handleLogin() {
        usernameText = usernameField.getText();
        passwordText = passwordField.getText();
        codeText = codeField.getText();

        if (Objects.equals(usernameText, "") || Objects.equals(passwordText, "")) {
            showAlert("用户名或密码不能为空！");
        } else if (Objects.equals(codeText, "")) {
            showAlert("验证码不能为空！");
        } else if (!codeText.equals(rightcodeText)) {
            showAlert("验证码错误！");
        } else {
            Connection connection = JDBC.getConnection();
            String sql = "select * from user where username='" + usernameText + "'";
            try {
                Statement statement = connection.createStatement();
                ResultSet resultSet = statement.executeQuery(sql);
                if (resultSet.next()) { // 用户存在
                    if (resultSet.getString("password").equals(passwordText)) { // 正确
                        User user = new User(usernameText);
                        user.setPassword(passwordText);
                        user.setExp(resultSet.getInt("exp"));
                        user.setHappyDou(resultSet.getInt("happyDou"));
                        new GameFX(user).start(new Stage());
                        ((Stage) loginButton.getScene().getWindow()).close();
                    } else { // 密码错误
                        showAlert("密码错误！");
                    }
                } else { // 用户不存在
                    showAlert("用户名不存在！");
                }
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
    }

    private void handleRegister() {
        new RegisterFX().start(new Stage());
        ((Stage) registerButton.getScene().getWindow()).close();
    }

    private void handleForgetPassword() {
        User user = new User(usernameText);
        new ForgetPasswordFX(user).start(new Stage());
        ((Stage) forgetPasswordLabel.getScene().getWindow()).close();
    }

    private void showAlert(String message) {
        javafx.scene.control.Alert alert = new javafx.scene.control.Alert(javafx.scene.control.Alert.AlertType.INFORMATION);
        alert.setTitle("提示");
        alert.setHeaderText(null);
        alert.setContentText(message);
        alert.showAndWait();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
